package nuig.prolog.userTypingFormat;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import nuig.prolog.PrologAccess.BaseProcess;
import nuig.prolog.PrologAccess.impl.WordProcess;
import nuig.prolog.entity.WordEntity;
import nuig.prolog.entity.WordType;
import nuig.prolog.userTypingFormat.impl.RuleContain;

/**
 * an abstract class as superclass
 * @author huangyuan
 *
 */
public abstract class  Rule {
	/**
	 * process list is the list to process and get the  result
	 */
	
	public static List< WordEntity > ProcessList =new ArrayList<WordEntity>();
	
	protected static StringBuilder ReturnMessage=new StringBuilder();

	
	
	public static StringBuilder getReturnMessage() {
		return ReturnMessage;
	}


	public static void setReturnMessage(StringBuilder returnMessage) {
		ReturnMessage = returnMessage;
	}


	/**
	 * get the user typing 
	 * @param userTyping
	 * @return
	 * @throws Exception 
	 */
	public  Rule DoRule(String userTyping) throws Exception
	{
		SetProcessList(userTyping);
		DoRule();		
		return this;		
	}
	
	
	/**
	 * do the chain to process the list
	 * @return
	 * @throws Exception 
	 */
	public abstract Rule DoRule() throws Exception;
	
	public  Rule DoRule(List<WordEntity> ProcessList) throws Exception
	{
		Rule.ProcessList = ProcessList;
		DoRule();
		return this;
	}

	public void SetProcessList(String userTyping) throws Exception
	{
		BaseProcess base=new BaseProcess();
		
		userTyping=userTyping.toLowerCase();//turn into lowerCase
		
		Pattern pattern = Pattern.compile("[, |]+");
		String[] strings = pattern.split(userTyping);
		
		ProcessList.removeAll(ProcessList);
		
		int i=0;
		for (String string : strings) {
			WordEntity word=new WordEntity();
			word.setID(i);
			word.setWord(string);
			//get the type of word
			
			if(base.isSuccess("word",string))
			{
				for (String t : WordType.TypeOfWord) {
					if(base.isSuccess(t,string))
					{
						word.setType(t);
						break;
					}
				}
				
			}else
			{
				word.setType("unknow");
			}
			
			ProcessList.add(word);			
			i++;
		}
		

		
	}
	
	
	public String GetString()
	{
		if(ProcessList.isEmpty())
		{
			return null;
		}else {
			StringBuilder sbBuilder=new StringBuilder();
			for (WordEntity word : ProcessList) {
				sbBuilder.append(word.getWord());
				
				sbBuilder.append(",");
			}
			
			return sbBuilder.substring(0, sbBuilder.length()-1).toString();	
		}
		
	}


}
